﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Roles;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Roles
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        IBaseRepository<RoleModel> roleRepo;
        IMapper mapper;

        public UpdateRoleHandler(IBaseRepository<RoleModel> roleRepo, IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var role = roleRepo.GetAll().Where(c => c.RoleName == request.RoleName && !c.IsDeleted &&  c.Id != request.Id).Count();
            if (role >0)
            {
                res.Msg = "角色名称不能重复";
                res.Code = ApiEnum.Fail;
                return Task.FromResult(res);
            }
            var roles=roleRepo.GetAll().Where(c=>c.Id==request.Id).FirstOrDefault();
            if(roles==null)
            {
                res.Msg = "角色名称不存在";
                res.Code = ApiEnum.Fail;
                return Task.FromResult(res);
            }
            roles.Updator = request.Updator;
            request.UpdatorDate = DateTime.Now;
            roles = mapper.Map(request,roles);
            int a = roleRepo.Update(roles).Result;
            if (a > 0)
            {
                res.Msg = "角色名称信息修改成功";
                res.Code = ApiEnum.Success;
                res.Datas = a;
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "角色名称信息修改失败";
                res.Code = ApiEnum.Success;
                res.Datas = a;
                return Task.FromResult(res);
            }
        }
    }
}
